import sys,io
from correlation import correlate
from PyQt5.QtCore import QThread,pyqtSignal
import threading
# 时长太短报错，需要调成cerrelation的span。五秒大概是20.min_overlap调小

# -w(不创建控制台)打包后变成None
if sys.stdout is not None:
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stdin is not None:
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

lock = threading.Lock()
class MusicMappingWorker(QThread):

    finishOneFile = pyqtSignal()
    workerFinished = pyqtSignal(object)
    workerTerminated = pyqtSignal(object)
    def __init__(self,startIndex,endIndex,keyFilePaths,valueFilePaths,excelData,foundedPaths):
        super(MusicMappingWorker,self).__init__()
        self.startIndex = startIndex
        self.endIndex = endIndex
        self.keyFilePaths = keyFilePaths
        self.valueFilePaths = valueFilePaths
        self.excelData = excelData
        self.foundedPaths = foundedPaths
        self._isRunning =False

    def run(self):
        self._isRunning = True
        for i in range(self.startIndex,self.endIndex):
            keyPath = self.keyFilePaths[i]

            maxSimilarity = 0
            maxSimilarityPath = ""

            founded = False
            for valuePath in self.valueFilePaths:                
                with lock:
                    if valuePath in  self.foundedPaths: #加锁
                        continue
                
                # 线程退出只需要在循环的耗时操作前检查一下就行了。
                if self._isRunning == False:
                    self.workerTerminated.emit(self)
                    return
                similarity = round(correlate(keyPath,valuePath))
                if similarity>maxSimilarity:
                    maxSimilarity = similarity
                    maxSimilarityPath = valuePath
                # 相似度>70直接认为同一首,并且其他曲子不用再比对这首
                if(similarity>70):
                    with lock:
                        self.foundedPaths.append(maxSimilarityPath) #加锁
                    founded = True
                    break
                if founded == True:
                    break
            founded = True

            self.excelData.insert(i,[keyPath,maxSimilarityPath,maxSimilarity])
            self.finishOneFile.emit()
        self.workerFinished.emit(self)

    def stop(self):
        self._isRunning=False